package com.pm.utils;

import com.pm.common.Response;
import com.pm.common.exception.ExpCodeState;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 上传工具
 * @author ht
 */
@Component
public class UploadUtil {

    /**
     * 文件上传工具
     * @param file     需要上传的文件
     * @param filePath 文件保存路径
     * @return
     * @throws Exception
     */
    public static Response uploadFile(MultipartFile file, String filePath) throws Exception {
        Map<String, Object> map = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        if (file.isEmpty()) {
            throw new Exception("上传失败，请选择文件！");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        File path = new File(filePath);
        if (!path.exists()) {
            path.mkdirs();
        }
        File targetFile = new File(filePath, fileName);
        FileUtils.writeByteArrayToFile(targetFile, file.getBytes());
//        FileCopyUtils.copy(file.getBytes(), targetFile);
        return new Response<>(ExpCodeState.upload_success, fileName);
    }
}
